package com.joker.registration.hosp.controller.api;

import com.joker.registration.hosp.service.HospitalService;
import com.joker.registration.hosp.service.HospitalSetService;
import com.registration.service.util.helper.HttpRequestHelper;
import com.registration.service.util.utils.MD5;
import exception.YyghException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import result.Result;
import result.ResultCodeEnum;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Api(tags = "医院管理api接口")
@RestController
@RequestMapping("/api/hosp")
public class ApiController {
    @Autowired
    private HospitalService hospitalService;

    @Autowired
    private HospitalSetService hospitalSetService;

    @ApiOperation(value = "上传医院")
    @PostMapping("saveHospital")
    public Result saveHospital(HttpServletRequest request) {
        //获得医院方传递过来的医院信息
        Map<String, String[]> requestMap = request.getParameterMap();
        //注意：上面获取医院方的数据，有些是String[]数组的形式，后面操作会比较麻烦一些
        //建议在此将String[]数组转换成Object对象形式，方便后面的操作
        //HttpRequestHelper工具类中的switchMap()方法，将Map<String, String[]>转换成Map<String, Object>

        Map<String, Object> paramMap = HttpRequestHelper.switchMap(requestMap);


        //1.获取医院方传递过来的签名，签名进行MD5加密
        String hospSign = (String) paramMap.get("sign");
        //2.根据传递过来的医院编码，查询数据库中该医院的签名
        String hoscode = (String)paramMap.get("hoscode");
        //0.如果hoscode为空，抛出参数异常
        if(StringUtils.isEmpty(hoscode)) {
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }

        String signKey = hospitalSetService.getSignKey(hoscode);
        //3.把数据库查询签名进行MD5加密
        String signKeyMd5 = MD5.encrypt(signKey);
        System.out.println(hospSign);
        System.out.println(signKeyMd5);
        //4.判断签名是否一致，如果不一致，则抛异常
        if(!hospSign.equals(signKeyMd5)){
//            throw new YyghException(ResultCodeEnum.SIGN_ERROR);
        }
        String save = hospitalService.save(paramMap);


        return Result.ok(save);
    }
}
